package com.example.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/api/wash/equipment")
@Tag(name = "设备管理", description = "洗护设备的管理和监控")
public class EquipmentController {

    @GetMapping("/status")
    @Operation(summary = "获取设备状态列表")
    public ResponseEntity<Map<String, Object>> getEquipmentStatus(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type) {

        // 模拟设备数据
        List<Map<String, Object>> equipmentList = Arrays.asList(
            createEquipmentData(1L, "洗衣机-001", "WASHING_MACHINE", "running", "正在洗涤", 85.5),
            createEquipmentData(2L, "洗衣机-002", "WASHING_MACHINE", "idle", "空闲中", 0.0),
            createEquipmentData(3L, "烘干机-001", "DRYER", "running", "正在烘干", 92.3),
            createEquipmentData(4L, "烘干机-002", "DRYER", "maintenance", "维护中", 0.0),
            createEquipmentData(5L, "熨烫机-001", "IRONING_MACHINE", "idle", "空闲中", 0.0),
            createEquipmentData(6L, "熨烫机-002", "IRONING_MACHINE", "running", "正在熨烫", 78.9)
        );

        // 过滤数据
        if (status != null && !status.isEmpty()) {
            equipmentList = equipmentList.stream()
                .filter(eq -> status.equals(eq.get("status")))
                .toList();
        }

        if (type != null && !type.isEmpty()) {
            equipmentList = equipmentList.stream()
                .filter(eq -> type.equals(eq.get("type")))
                .toList();
        }

        // 分页处理
        int start = page * size;
        int end = Math.min(start + size, equipmentList.size());
        List<Map<String, Object>> pagedList = start < equipmentList.size() ? 
            equipmentList.subList(start, end) : new ArrayList<>();

        Map<String, Object> response = new HashMap<>();
        response.put("content", pagedList);
        response.put("totalElements", equipmentList.size());
        response.put("totalPages", (int) Math.ceil((double) equipmentList.size() / size));
        response.put("size", size);
        response.put("number", page);

        return ResponseEntity.ok(response);
    }

    @GetMapping
    @Operation(summary = "获取设备列表")
    public ResponseEntity<Map<String, Object>> getEquipmentList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        return getEquipmentStatus(page, size, null, null);
    }

    @PostMapping
    @Operation(summary = "添加新设备")
    public ResponseEntity<Map<String, Object>> addEquipment(@RequestBody Map<String, Object> equipment) {
        Map<String, Object> newEquipment = createEquipmentData(
            System.currentTimeMillis(),
            (String) equipment.get("name"),
            (String) equipment.get("type"),
            "idle",
            "新设备",
            0.0
        );
        return ResponseEntity.ok(newEquipment);
    }

    @PutMapping("/{id}/status")
    @Operation(summary = "更新设备状态")
    public ResponseEntity<Map<String, Object>> updateEquipmentStatus(
            @PathVariable Long id,
            @RequestBody Map<String, Object> statusUpdate) {
        
        String newStatus = (String) statusUpdate.get("status");
        Map<String, Object> equipment = createEquipmentData(
            id,
            "设备-" + id,
            "WASHING_MACHINE",
            newStatus,
            getStatusDescription(newStatus),
            "running".equals(newStatus) ? 85.5 : 0.0
        );
        
        return ResponseEntity.ok(equipment);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除设备")
    public ResponseEntity<Void> deleteEquipment(@PathVariable Long id) {
        return ResponseEntity.ok().build();
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取设备统计信息")
    public ResponseEntity<Map<String, Object>> getEquipmentStatistics() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("total", 6);
        stats.put("running", 3);
        stats.put("idle", 2);
        stats.put("maintenance", 1);
        stats.put("offline", 0);
        stats.put("efficiency", 87.5); // 设备利用率
        
        return ResponseEntity.ok(stats);
    }

    @PostMapping("/{id}/maintenance")
    @Operation(summary = "安排设备维护")
    public ResponseEntity<Map<String, Object>> scheduleMaintenanceEquipment(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "设备维护已安排");
        result.put("maintenanceTime", LocalDateTime.now().plusHours(2));
        
        return ResponseEntity.ok(result);
    }

    // 辅助方法：创建设备数据
    private Map<String, Object> createEquipmentData(Long id, String name, String type, 
                                                   String status, String description, Double efficiency) {
        Map<String, Object> equipment = new HashMap<>();
        equipment.put("id", id);
        equipment.put("name", name);
        equipment.put("type", type);
        equipment.put("status", status);
        equipment.put("description", description);
        equipment.put("efficiency", efficiency);
        equipment.put("location", "车间A");
        equipment.put("model", "XY-2024");
        equipment.put("installDate", "2024-01-15");
        equipment.put("lastMaintenance", "2024-05-20");
        equipment.put("nextMaintenance", "2024-08-20");
        equipment.put("workingHours", 1250);
        equipment.put("createTime", LocalDateTime.now().minusDays(30));
        equipment.put("updateTime", LocalDateTime.now());
        
        return equipment;
    }

    // 辅助方法：获取状态描述
    private String getStatusDescription(String status) {
        return switch (status) {
            case "running" -> "运行中";
            case "idle" -> "空闲中";
            case "maintenance" -> "维护中";
            case "offline" -> "离线";
            default -> "未知状态";
        };
    }
}
